package lesson.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lesson.entity.HealthClock;
import lesson.entity.NocvData;
import lesson.service.HealthClockService;
import lesson.service.IndexService;
import lesson.vo.DataView;
import lesson.vo.HealthClockVo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: Wanzhen
 * @Date: 2022/6/11-20:42
 */
@Controller
public class HealthClockController {

    @Autowired
    private HealthClockService healthClockService;

    @Autowired
    private IndexService indexService;

    @RequestMapping("/toHealthClock")
    public String toHealthClock(){
        return "/admin/healthclock";
    }

    /**
     * 查询所有打卡记录，带有模糊查询条件，带有分页
     * @param healthClockVo
     * @return
     */
    @RequestMapping("/listHealthClock")
    @ResponseBody
    public DataView listHealthClock(HealthClockVo healthClockVo){
        //查询所有带有模糊查询条件，带有分页
        IPage<HealthClock> page = new Page<>(healthClockVo.getPage(), healthClockVo.getLimit());
        QueryWrapper<HealthClock> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(healthClockVo.getUsername() != null, "username",healthClockVo.getUsername());
        queryWrapper.eq(healthClockVo.getPhone() != null ,"phone", healthClockVo.getPhone());
        healthClockService.page(page, queryWrapper);
        DataView dataView = new DataView(page.getTotal(), page.getRecords());
        return dataView;
    }

    /**
     * 添加或修改健康打卡记录数据
     * @param healthClock
     * @return
     */
    @RequestMapping("/addHealthClock")
    @ResponseBody
    public DataView addHealthClock(HealthClock healthClock){
        boolean saveOrUpdate = healthClockService.saveOrUpdate(healthClock);
        DataView dataView = new DataView();
        if(saveOrUpdate){
            dataView.setCode(200);
            dataView.setMsg("修改打卡记录成功！");
        }
        dataView.setCode(100);
        dataView.setMsg("增加打卡记录成功！");
        return dataView;
    }

    /**
     * 删除记录
     * @param id
     * @return
     */
    @RequestMapping("/deleteHealthClockById")
    @ResponseBody
    public DataView deleteHealthClockById(Integer id){
        healthClockService.removeById(id);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("打卡记录删除成功");
        return dataView;
    }

    /**
     * Excel的拖拽或点击上传
     */
    @RequestMapping("/excelImportChina")
    @ResponseBody
    public DataView excelImportChina(@RequestParam("file")MultipartFile file) throws Exception {
        DataView dataView = new DataView();
        //1.文件不能为空
        if(file.isEmpty()){
            dataView.setMsg("文件为空，不能上传");
        }
        //2.POI获取excel解析数据
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        HSSFSheet sheet = wb.getSheetAt(0);
        //3.定义一个集合，接收文件中数据
        List<NocvData> list = new ArrayList<>();
        HSSFRow row = null;
        //4.解析数据，装到集合中
        for(int i = 0;i < sheet.getPhysicalNumberOfRows();i++){
            //4.1定义实体
            NocvData nocvData = new NocvData();
            //4.2获取每一行的数据，放到实体类中
            row = sheet.getRow(i);
            //4.3解析数据
            nocvData.setName(row.getCell(0).getStringCellValue());
            nocvData.setValue((int) row.getCell(1).getNumericCellValue());
            //5.添加list集合
            list.add(nocvData);
        }
        //6.mybatis-plus批量插入数据库
        indexService.saveBatch(list);
        dataView.setCode(200);
        dataView.setMsg("小可爱，excel已经上传啦~");
        return dataView;
    }

    /**
     * 导出中国疫情excel数据
     */
    @RequestMapping("/excelOutPortChina")
    @ResponseBody
    public void excelOutPortChina(HttpServletResponse response) throws Exception {
        //1.查询数据库(查询所有，符合条件的数据)
        List<NocvData> list = indexService.list();
        //2.建立Excel对象，封装数据
        response.setCharacterEncoding("UTF-8");
        //2.1创建Excel对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //2.2创建sheet对象
        HSSFSheet sheet = wb.createSheet("中国疫情数据sheet1");
        //2.3创建表头
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("城市名称");
        row.createCell(1).setCellValue("确诊数量");
        //3.遍历数据，封装Excel工作对象
        for(NocvData data : list){
            HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1);
            row1.createCell(0).setCellValue(data.getName());
            row1.createCell(1).setCellValue(data.getValue());
        }
        OutputStream os = null;
        try {
            //4.建立输出流，输出浏览器文件
            os = null;
            //4.1设置xxx.excel
            response.setContentType("application/octet-stream;chartset=utf8");
            response.setHeader("content-Disposition", "attachment;filename="+
                    new String("中国疫情数据表".getBytes(), "iso-8859-1") + ".xls");
            //4.2输出文件
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os != null){
                    //5.关闭输出流
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
